package com.gz.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

//import org.bouncycastle.crypto.tls.AlertDescription;

//import freemarker.core._RegexBuiltins.split_reBI;

/**
 * 短信验证工具类
 */
public class SendSMSUtil {
	
	public static String getCode() {
		int  code = (int)((Math.random()*9+1)*100000); 
		return code+"";
	}
	
	public static String getContent(String code) {
		String content = "【车主联盟】"+code+" （平台注册验证码，5分钟内有效）";
		//【车主联盟】435386 （平台注册验证码，5分钟内有效）
		return content;
	}
	
	public static boolean sendSMS(String mobile,String content) {
		boolean sendStatus = false;
		try {
			String urlPath = "http://47.104.131.56:8868/sms.aspx";
			//String urlPath = new String("http://localhost:8080/Test1/HelloWorld");   
	        //String urlPath = new String("http://localhost:8080/Test1/HelloWorld?name=丁丁".getBytes("UTF-8"));
	        String param="action=send&userid=157&account=chezhulianmeng&password=chezhulianmeng123&mobile="+mobile+"&content="+URLEncoder.encode(content,"UTF-8")+"&sendTime=";
	         
	        //建立连接
	        URL url=new URL(urlPath);
	        HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
	         
	        //设置参数
	        httpConn.setDoOutput(true);     //需要输出
	        httpConn.setDoInput(true);      //需要输入
	        httpConn.setUseCaches(false);   //不允许缓存
	        httpConn.setRequestMethod("POST");      //设置POST方式连接
	         
	        //设置请求属性
	        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	        httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
	        httpConn.setRequestProperty("Charset", "UTF-8");
	         
	        //连接,也可以不用明文connect，使用下面的httpConn.getOutputStream()会自动connect
	        httpConn.connect();
	             
	        //建立输入流，向指向的URL传入参数
	        DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream());
	        dos.writeBytes(param);
	        dos.flush();
	        dos.close();
	         
	        //获得响应状态
	        String rs= "";
	        int resultCode=httpConn.getResponseCode();
	        if(HttpURLConnection.HTTP_OK==resultCode){
	            StringBuffer sb=new StringBuffer();
	            String readLine=new String();
	            BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
	            while((readLine=responseReader.readLine())!=null){
	                sb.append(readLine).append("\n");
	            }
	            responseReader.close();
	            rs= sb.toString();
	        } 
	        //System.out.println(rs);
	        if(rs.indexOf("Success")>=0) {
	        	sendStatus=true;
	        }else {
	        	sendStatus=false;
	        }
		} catch (Exception e) {
			// TODO: handle exception
		}
		return sendStatus;
	}
}
